import { SquareGrounp } from "../SquareGrounp";
import { GameStatus, GameViewer } from "../types";
import { SquarePageViewer } from "./SquarePageViewer";
import $ from 'jquery'
import { Game } from "../Game";
import GameConfig from "../GameConfig";
import PageConfig from "./PageConfig";

export class GamePageViewer implements GameViewer {

  private rootDom: JQuery<HTMLElement> = $('#root')
  private nextDom: JQuery<HTMLElement> = $('#next')
  private scoreDom: JQuery<HTMLElement> = $('#score')
  private msgDom: JQuery<HTMLElement> = $('#msg')


  // 游戏初始化
  init(game: Game): void {
    // 设置区域宽高
    const { panelSize, nextSize } = GameConfig
    const SquareSize = PageConfig.SquareSize
    // 游戏面板
    this.rootDom.css({
      width: panelSize.width * SquareSize.width + 'px',
      height: panelSize.height * SquareSize.height + 'px',
    })
    // 下一个方块
    this.nextDom.css({
      width: SquareSize.width * nextSize.width + 'px',
      height: SquareSize.height * nextSize.height + 'px',
    })

    // 注册键盘事件
    $(document).keydown(e => {
      e.keyCode == 37 && game.controlLeft()  // 左
      e.keyCode == 38 && game.controlRotate()  // 上 旋转
      e.keyCode == 39 && game.controlRight()  // 右
      e.keyCode == 40 && game.controlDown()  // 下

      if (e.keyCode == 32) { // 空格
        if (game.gameStatus == GameStatus.init) {game.start()}
        else if (game.gameStatus == GameStatus.playing) {game.pause()}
        else if (game.gameStatus == GameStatus.pause) {game.start()}
        else if (game.gameStatus == GameStatus.over) {game.start()}
      }
    })


  }
  // 显示分数
  showScore(score: number): void {
    this.scoreDom.text(score)
  }

  // 显示下一个方块
  showNext(teris: SquareGrounp): void {
    teris.squares.forEach(sq => {
      sq.viewer = new SquarePageViewer(sq, $("#next"))
    })
  }
  // 切换方块
  switch(teris: SquareGrounp): void {
    teris.squares.forEach(sq => {
      sq.viewer?.remove()
      sq.viewer = new SquarePageViewer(sq, $("#panel"))
    })
  }

  onGamePause(): void {
    this.msgDom.css({display:'flex'})
    this.msgDom.find('p').html("游戏暂停")
  }

  onGameStart(): void {
    this.msgDom.hide()
  }

  onGameOver(): void {
    this.msgDom.css({display:'flex'})
    this.msgDom.find('p').html("游戏结束")
  }

}